package org.dxy.ai.controller;



import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.api.dto.response.R;
import org.dxy.ai.dto.ChatRequest;
import org.dxy.ai.dto.ChatSessionDto;
import org.dxy.ai.service.Assistant;
import org.dxy.ai.service.ChatSessionService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.util.List;
import java.util.Map;


/**
 * @ description: AI聊天控制器
 * @ author: dxy
 * @ createTime: 2025/10/5 1:11
 */

@Slf4j
@RestController
@RequestMapping("/api/v1/chat")
@RequiredArgsConstructor
public class ChatController {

    private final Assistant assistant;
    private final ChatSessionService chatSessionService;



    /**
     * 同步聊天接口 — 一次性返回完整结果
     */
    @PostMapping("/askSync")
    public R<String> askSync(@RequestBody ChatRequest request) {
        try {
            log.info("[同步聊天] 收到请求: {}", request.getMessage());
            String result = assistant.chatSync(request.getMessage());

            // 清除 <think>...</think> 标签及其内容（非贪婪匹配）
            result = result.replaceAll("(?s)<think>.*?</think>", "").trim();

            log.info("[同步聊天] AI 回复: {}", result);
            return R.ok(result, "回复成功");
        } catch (Exception e) {
            log.error("[同步聊天] AI聊天异常", e);
            return R.fail("AI服务暂时不可用，请稍后重试");
        }
    }



    @PostMapping(value = "/askStream", produces = MediaType.TEXT_XML_VALUE)
    public Flux<String> ask(@RequestBody ChatRequest request) {
        log.info("收到聊天请求: {}", request.toString());
//        return assistant.chatStream(request.getMemoryId(), request.getMessage());

        // 1️⃣ 将阻塞调用放到 boundedElastic(防止异步返回变为阻塞)
        return Mono.fromCallable(() -> assistant.chatStream(request.getMemoryId(), request.getMessage()))
                .subscribeOn(Schedulers.boundedElastic()) // ✅ 切换线程池
                // 2️⃣ 转为 Flux 流
                .flatMapMany(flux -> flux);
    }

    /**
     * 创建新会话
     */
    @PostMapping("/session/create")
    public R<Map<String, String>> createSession() {
        try {
            String sessionId = chatSessionService.createSession();
            log.info("[会话管理] 创建新会话: {}", sessionId);
            return R.ok(Map.of("sessionId", sessionId), "会话创建成功");
        } catch (Exception e) {
            log.error("[会话管理] 创建会话失败", e);
            return R.fail("创建会话失败");
        }
    }

    /**
     * 获取会话列表
     */
    @GetMapping("/sessions")
    public R<List<ChatSessionDto>> getSessions() {
        try {
            List<ChatSessionDto> sessions = chatSessionService.getAllSessions();
            log.info("[会话管理] 获取会话列表，共{}个会话", sessions.size());
            return R.ok(sessions, "获取成功");
        } catch (Exception e) {
            log.error("[会话管理] 获取会话列表失败", e);
            return R.fail("获取会话列表失败");
        }
    }

    /**
     * 删除会话
     */
    @DeleteMapping("/session/{sessionId}")
    public R<Void> deleteSession(@PathVariable String sessionId) {
        try {
            chatSessionService.deleteSession(sessionId);
            log.info("[会话管理] 删除会话: {}", sessionId);
            return R.ok(null, "会话删除成功");
        } catch (Exception e) {
            log.error("[会话管理] 删除会话失败: {}", sessionId, e);
            return R.fail("删除会话失败");
        }
    }

    /**
     * 更新会话标题
     */
    @PutMapping("/session/{sessionId}/title")
    public R<Void> updateSessionTitle(@PathVariable String sessionId, @RequestBody Map<String, String> request) {
        try {
            String title = request.get("title");
            chatSessionService.updateSessionTitle(sessionId, title);
            log.info("[会话管理] 更新会话标题: {} -> {}", sessionId, title);
            return R.ok(null, "标题更新成功");
        } catch (Exception e) {
            log.error("[会话管理] 更新会话标题失败: {}", sessionId, e);
            return R.fail("更新标题失败");
        }
    }

}
